<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="65%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="服务单元名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入服务单元名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="belongDepart">
            <el-tree-select
              v-model="formData.belongDepart"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择所属部门"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="服务类型" prop="serviceType">
            <el-select
              v-model="formData.serviceType"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择服务类型"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_SERVICE_UNIT_SERVICE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否测试单元" prop="isTestUnit">
            <el-select v-model="formData.isTestUnit" placeholder="请选择是否测试单元">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_SERVICE_UNIT_IS_TEST)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="是否发起收款任务" prop="isReceiveMoney">
            <el-input v-model="formData.isReceiveMoney" placeholder="请输入是否发起收款任务" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收款负责人类型" prop="receiveMoneyType">
            <el-select
              v-model="formData.receiveMoneyType"
              placeholder="请选择运维类合同收款负责人类型"
            >
              <el-option label="请选择字典生成" value="" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="服务区域" prop="serviceArea">
            <el-input v-model="formData.serviceArea" placeholder="请输入服务区域" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="驻点地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入驻点地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="经度" prop="lng">
            <el-input v-model="formData.lng" placeholder="请输入经度" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="纬度" prop="lat">
            <el-input v-model="formData.lat" placeholder="请输入纬度" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button plain type="primary" @click="openBaiduMapDialog">定位</el-button>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <BaiduMapDialog ref="baiduMapDialogRef" @success="handleBaiduMapPosition" />
</template>
<script setup lang="ts">
import {
  CustomerArchiveServiceUnitApi,
  CustomerArchiveServiceUnit
} from '@/api/biz/customer/serviceunit'

import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import BaiduMapDialog from '../../component/BaiduMap.vue'

/** 客户档案-服务单元管理 表单 */
defineOptions({ name: 'CustomerArchiveServiceUnitForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  belongDepart: undefined,
  serviceType: undefined,
  isTestUnit: undefined,
  isReceiveMoney: undefined,
  receiveMoneyType: undefined,
  serviceArea: undefined,
  address: undefined,
  lng: undefined,
  lat: undefined,
  ownerUserId: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CustomerArchiveServiceUnitApi.getCustomerArchiveServiceUnit(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerArchiveServiceUnit
    if (formType.value === 'create') {
      await CustomerArchiveServiceUnitApi.createCustomerArchiveServiceUnit(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerArchiveServiceUnitApi.updateCustomerArchiveServiceUnit(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    belongDepart: undefined,
    serviceType: undefined,
    isTestUnit: undefined,
    isReceiveMoney: undefined,
    receiveMoneyType: undefined,
    serviceArea: undefined,
    address: undefined,
    lng: undefined,
    lat: undefined,
    ownerUserId: undefined
  }
  formRef.value?.resetFields()
}

/** 打开百度地图 */
const baiduMapDialogRef = ref()
const openBaiduMapDialog = () => {
  baiduMapDialogRef.value.open()
}

const handleBaiduMapPosition = (addressInfo) => {
  if (addressInfo !== undefined) {
    formData.value.lng = addressInfo.longitude.toFixed(4)
    formData.value.lat = addressInfo.latitude.toFixed(4)
  }
}
</script>
